import { inject, reactive, readonly, type App } from "vue";
import * as userServ from "../api/user";

export type TUser = {
  loginId?: string;
  loginPwd?: string;
  name?: string;
};

export type IState = {
  user: TUser | null;
  loading: boolean;
};

const key = Symbol(); // Provide的key

export function provideStore(app: App<Element>) {
  const state = reactive<IState>({ user: null, loading: false });

  async function login(loginId: string, loginPwd: string) {
    state.loading = true;
    const user = await userServ.login(loginId, loginPwd);
    state.user = user;
    state.loading = false;
  }

  // 退出
  async function loginOut() {
    state.loading = true;
    await userServ.loginOut();
    state.loading = false;
    state.user = null;
  }
  // 恢复登录状态
  async function whoAmI() {
    state.loading = true;
    const user = await userServ.whoAmI();
    state.loading = false;
    state.user = user;
  }

  app.provide(key, {
    state: readonly(state), // 对外只读
    login,
    loginOut,
    whoAmI,
  });
}

export function useStore(defaultValue = null) {
  return inject(key, defaultValue) as unknown as {
    state: Readonly<IState>;
    login: (loginId: string, loginPwd: string) => Promise<void>;
    loginOut: () => Promise<void>;
    whoAmI: () => Promise<void>;
  };
}
